package top.iszsq.config.convert;

import org.springframework.core.convert.converter.Converter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 字符转LocalDateTime对象
 * @author zsq
 * @date 2021/8/28 11:33
 **/
public class DateTimeConverter implements Converter<String, LocalDateTime> {

    private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public LocalDateTime convert(String dateStr) {
        if (dateStr == null || dateStr.trim().equals("")) {
            return null;
        }

        LocalDateTime parse = null;
        if (dateStr != null && !"".equals(dateStr.trim())) {
            try {
                parse = LocalDateTime.parse(dateStr, dateFormatter);
            } catch (Exception e) {
                //使用默认的转换格式
                parse = LocalDateTime.parse(dateStr);
            }
        }
        return parse;
    }

}
